package com.kye.express.business.home;

import android.arch.lifecycle.Lifecycle;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.kye.base.Logger;
import com.kye.base.utils.GsonUtils;
import com.kye.express.R;
import com.kye.express.business.customer_code.bind_customer_code.BindCustomerCodeActivity;
import com.kye.express.business.home.viewmodel.NoticeModel;
import com.kye.express.business.login.LoginActivity;
import com.kye.express.business.web.KyeWebActivity;
import com.kye.express.contract.base.BasePresenter;
import com.kye.express.contract.base.view.IView;
import com.kye.express.databinding.FragmentMainHomeBinding;
import com.kye.express.view.ToastManager;
import com.kye.model.OpenApiResultObserver;
import com.kye.model.UserSession;
import com.kye.model.base.RetrofitManager;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.advertisement.AdvertisementBean;
import com.kye.model.bean.advertisement.AdvertisementType;
import com.kye.model.bean.deposit.RequestJudgeStoredQuery;
import com.kye.model.bean.deposit.ResultJudgeStoredQueryBean;
import com.kye.model.bean.freight_rates_query.GetCustomerInfoResultBean;
import com.kye.model.bean.freight_rates_query.PermissionQueryCostResultBean;
import com.kye.model.bean.freight_rates_query.RequestGetCustomerInfoBean;
import com.kye.model.bean.freight_rates_query.RequestPermissionQueryCostBean;
import com.kye.model.bean.logistics.LogisticsSendAndReceiveRecordBean;
import com.kye.model.bean.logistics.request.RequestLogisticsSendAndReceiveRecords;
import com.kye.model.bean.notice.NotificationListResultBean;
import com.kye.model.bean.notice.request.NotificationListRequestParam;
import com.kye.model.bean.president_online.PermissionForPresidentOnlineBean;
import com.kye.model.bean.president_online.RequestPermissionForPresidentOnlineBean;
import com.kye.model.bean.user.User;
import com.kye.model.datasource.AdvertisementDataSource;
import com.kye.model.datasource.LogisticsDataSource;
import com.kye.model.datasource.NotificationDataSource;
import com.kye.model.service.AdvertisementService;
import com.kye.model.service.DepositService;
import com.kye.model.service.FreightRatesQueryService;
import com.kye.model.service.PresidentOnlineService;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 18/12/2017
 * @updated : 18/12/2017
 * @description : <Description>
 * @update_reason : <UpdateReason>
 */

public interface HomeContract {

    interface HomeView extends IView {

        void initNoticeMarquee(List<View> views);

        void onUser(User user);

        void initBannerView(ArrayList<String> adImages);

        FragmentMainHomeBinding getDataBinding();

        Context getContext();

        void onPresidentOnlinePermission(PermissionForPresidentOnlineBean permissionForPresidentOnline, boolean startPresidentOnlinePage);

        void onPermissionForQueryFreightRates(OpenApiResult<PermissionQueryCostResultBean> resultBean, boolean startFreightRatesPage);

        void onGetCustomerInfoLoaded(GetCustomerInfoResultBean resultBean);

        void onGetCustomerInfoComplete();

        void onGetCustomerInfoError(String msg);

        void onGetCustomerInfoLoading();

        void updateLogisticsSendAndReceiveRecords(LogisticsSendAndReceiveRecordBean logisticsSendAndReceiveRecordBeans);

        void getLogisticsSendAndReceiveRecordsFailed(OpenApiResult<LogisticsSendAndReceiveRecordBean> result);

        void getLogisticsSendAndReceiveRecordsFailed(Throwable throwable);

//        void updateLogisticsRecordSendAndReceive(RecordAmountModel recordAmountModel);

        void onDepositLoading();

        void onDepositComplete();

        void onDepositSuccess(OpenApiResult<ResultJudgeStoredQueryBean> bean);

        void onDepositError(OpenApiResult<ResultJudgeStoredQueryBean> result, int code, String msg);

        void onDepositOtherError(Throwable e);

        Context getCtx();
    }

    class HomePresenter extends BasePresenter<HomeView> {

        private Context mContext;

        private String TAG_ADS = "TAG_ADS"; // 首页轮播广告, banner
        private String TAG_ADS_IMGS = "TAG_ADS_IMGS";
        private String TAG_NOTIFICATION_LIST = "TAG_NOTIFICATION_LIST"; // 首页轮播通知，6条通知
        @Deprecated
        private AdvertisementDataSource advertisementDataSource;
        private AdvertisementService advertisementService;
        private NotificationDataSource notificationDataSource;
        private LogisticsDataSource logisticsDataSource;
        private Observable<User> userObservable;
        private User userInfo;

        private ArrayList<AdvertisementBean> advertisementBeans = new ArrayList<>();
        private ArrayList<String> advertisementImages = new ArrayList<>();
        private List<NoticeModel> noticeDatas = new ArrayList<>(); // for test
        private NotificationListResultBean notificationListResultBean;

        public HomePresenter(Context context) {
            mContext = context;
            advertisementDataSource = new AdvertisementDataSource();
            advertisementService = RetrofitManager.getInstance().createOpenApiService(AdvertisementService.class);
            notificationDataSource = new NotificationDataSource();
            logisticsDataSource = new LogisticsDataSource();
        }

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (savedInstanceState != null) {
                advertisementBeans = savedInstanceState.getParcelableArrayList(TAG_ADS);
                advertisementImages = savedInstanceState.getStringArrayList(TAG_ADS_IMGS);
                notificationListResultBean = savedInstanceState.getParcelable(TAG_NOTIFICATION_LIST);
            }
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            outState.putParcelableArrayList(TAG_ADS, advertisementBeans);
            outState.putStringArrayList(TAG_ADS_IMGS, advertisementImages);
            outState.putParcelable(TAG_NOTIFICATION_LIST, notificationListResultBean);
            super.onSaveInstanceState(outState);
        }

        @Override
        public void bind(HomeView view) {
            super.bind(view);
            userObservable = UserSession.getInstance()
                    .getUserForRx()
                    .compose(getView().getProvider().<User>bindUntilEvent(Lifecycle.Event.ON_DESTROY))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
        }

        public void initBannerData() {
            advertisementDataSource
                    .getAdvertisementList(AdvertisementType.TYPE_AD_BANNER_HOME)
                    .compose(getView().bindToLifecycleDestroy())
                    .subscribeOn(Schedulers.io())
                    .toObservable()
                    .flatMap(new Function<List<AdvertisementBean>, ObservableSource<AdvertisementBean>>() {
                        @Override
                        public ObservableSource<AdvertisementBean> apply(List<AdvertisementBean> advertisementBeans) throws Exception {
                            return Observable.fromIterable(advertisementBeans);
                        }
                    })
                    .take(8) // todo : 数据过多
                    .reduce(new Pair<List<String>, List<AdvertisementBean>>(new ArrayList<String>(), new ArrayList<AdvertisementBean>()),
                            new BiFunction<Pair<List<String>, List<AdvertisementBean>>, AdvertisementBean, Pair<List<String>, List<AdvertisementBean>>>() {
                                @Override
                                public Pair<List<String>, List<AdvertisementBean>> apply(Pair<List<String>, List<AdvertisementBean>> listListPair, AdvertisementBean advertisementBean) throws Exception {
                                    Logger.d("advertisement item : \n" + GsonUtils.toJsonString(advertisementBean, true));
                                    listListPair.first.add(advertisementBean.getSmallImg());
                                    listListPair.second.add(advertisementBean);
                                    return listListPair;
                                }
                            })
                    .observeOn(AndroidSchedulers.mainThread());
            /**
             * todo : following is depredated
             */
//                    .subscribe(new SingleObserver<Pair<List<String>, List<AdvertisementBean>>>() {
//                        @Override
//                        public void onSubscribe(Disposable d) {
//                            addDisposable(d);
//                        }
//
//                        @Override
//                        public void onSuccess(Pair<List<String>, List<AdvertisementBean>> listListPair) {
//                            getView().getDataBinding().refreshLayout.finishRefresh(true);
//                            Logger.d("onSuccess : " + listListPair.first.size() + " : " + listListPair.second.size());
//                            if (listListPair.second == null || listListPair.second.size() <= 0) {
//                                // empty
//
//                            } else {
//                                // success
//                                advertisementImages = (ArrayList<String>) listListPair.first;
//                                advertisementBeans = (ArrayList<AdvertisementBean>) listListPair.second;
//                                getView().initBannerView(advertisementImages);
//                            }
//                        }
//
//                        @Override
//                        public void onError(Throwable e) {
//                            if (e instanceof CancellationException) {
//                                return;
//                            }
//                            // error
//                            Logger.d("onError : " + e.getMessage());
//                            getView().getDataBinding().refreshLayout.finishRefresh(false);
//                        }
//                    });

            advertisementService
                    .getAdvertisementList(new Object())
                    .compose(getView().bindToLifecycleDestroy())
                    .observeOn(Schedulers.io())
                    .subscribeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<List<AdvertisementBean>>() {
                        @Override
                        public void onLoading(Disposable d) {

                        }

                        @Override
                        public void onLoaded() {

                        }

                        @Override
                        public void onSuccess(OpenApiResult<List<AdvertisementBean>> result, List<AdvertisementBean> advertisementBeans) {
                            handleAdvertisementDatas(advertisementBeans);
                        }

                        @Override
                        public void onApiError(OpenApiResult<List<AdvertisementBean>> result, int code, String msg) {
                            Logger.d("onApiError : " + msg);
                            getView().getDataBinding().refreshLayout.finishRefresh(true);
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            Logger.d("onError : " + e.getMessage());
                            getView().getDataBinding().refreshLayout.finishRefresh(false);
                        }

                        @Override
                        public void onDisposed(Throwable e) {
                            Logger.d("onDisposed : " + e.getMessage());
                        }
                    });
        }

        private void handleAdvertisementDatas(List<AdvertisementBean> advertises) {
            Observable.fromIterable(advertises)
                    .filter(new Predicate<AdvertisementBean>() {
                        @Override
                        public boolean test(AdvertisementBean advertisementBean) throws Exception {
                            return advertisementBean.getClassid() == AdvertisementType.TYPE_AD_BANNER_HOME.getClassid();
                        }
                    })
                    .take(8)
                    .reduce(new Pair<List<String>, List<AdvertisementBean>>(new ArrayList<String>(), new ArrayList<AdvertisementBean>()),
                            new BiFunction<Pair<List<String>, List<AdvertisementBean>>, AdvertisementBean, Pair<List<String>, List<AdvertisementBean>>>() {
                                @Override
                                public Pair<List<String>, List<AdvertisementBean>> apply(Pair<List<String>, List<AdvertisementBean>> listListPair, AdvertisementBean advertisementBean) throws Exception {
                                    Logger.d("advertisement item : \n" + GsonUtils.toJsonString(advertisementBean, true));
                                    listListPair.first.add(advertisementBean.getSmallImg());
                                    listListPair.second.add(advertisementBean);
                                    return listListPair;
                                }
                            })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SingleObserver<Pair<List<String>, List<AdvertisementBean>>>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onSuccess(Pair<List<String>, List<AdvertisementBean>> listListPair) {
                            // success
                            advertisementImages = (ArrayList<String>) listListPair.first;
                            advertisementBeans = (ArrayList<AdvertisementBean>) listListPair.second;
                            getView().initBannerView(advertisementImages);
                        }

                        @Override
                        public void onError(Throwable e) {
                            getView().getDataBinding().refreshLayout.finishRefresh(false);
                        }
                    });
        }

        public void onBannerItemSelected(int position) {
//            Logger.d("onBannerItemSelected : position : " + position + " item : \n " + GsonUtils.toJsonString(advertisementBeans.get(position), true));
            AdvertisementBean advertisementBean = advertisementBeans.get(position);
            if (!TextUtils.isEmpty(advertisementBean.getAccessUrl())) {
                KyeWebActivity.startActivity(getView().getCtx(), advertisementBean.getAccessUrl(), advertisementBean.getAdName(), false);
            }
        }

        public void initNotification() {
            NotificationListRequestParam param = new NotificationListRequestParam();
            param.setAction(String.valueOf(1));
            param.setPageSize(6);
            param.setPageNum(1);
            notificationDataSource
                    .getNotificationList(param)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<NotificationListResultBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onSuccess(OpenApiResult<NotificationListResultBean> result, NotificationListResultBean notificationListResultBean) {
                            Logger.d("onSuccess : \n" + GsonUtils.toJsonString(result, true));
                            HomePresenter.this.notificationListResultBean = notificationListResultBean;
                            initNotificationView(notificationListResultBean);
                        }

                        @Override
                        public void onApiError(OpenApiResult<NotificationListResultBean> result, int code, String msg) {
                            Logger.d("onApiError : \n" + GsonUtils.toJsonString(result, true));

                        }

                        @Override
                        public void onOtherError(Throwable e) {

                        }

                        @Override
                        public void onLoaded() {

                        }
                    });

        }

        private void initNotificationView(final NotificationListResultBean notificationListResultBean) {
            Observable
                    .fromIterable(notificationListResultBean.getDatas())
                    .buffer(3)
                    .subscribeOn(Schedulers.io())
                    .map(new Function<List<NotificationListResultBean.NotificationListItemBean>, List<NotificationListResultBean.NotificationListItemBean>>() {
                        @Override
                        public List<NotificationListResultBean.NotificationListItemBean> apply(List<NotificationListResultBean.NotificationListItemBean> notificationListItemBeans) throws Exception {
                            if (notificationListItemBeans.size() < 3) {
                                notificationListItemBeans.addAll(notificationListResultBean.getDatas().subList(0, 3 - notificationListItemBeans.size()));
                            }
                            return notificationListItemBeans;
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .map(new Function<List<NotificationListResultBean.NotificationListItemBean>, View>() {
                        @Override
                        public View apply(List<NotificationListResultBean.NotificationListItemBean> notificationListItemBeans) throws Exception {
                            View view = LayoutInflater.from(getView().getContext()).inflate(R.layout.layout_notice_marquee, null);
                            TextView tvNotice0 = view.findViewById(R.id.tvNotice0);
                            TextView tvNotice1 = view.findViewById(R.id.tvNotice1);
                            TextView tvNotice2 = view.findViewById(R.id.tvNotice2);
                            tvNotice0.setText(notificationListItemBeans.get(0).getMsgTitle());
                            tvNotice1.setText(notificationListItemBeans.get(1).getMsgTitle());
                            tvNotice2.setText(notificationListItemBeans.get(2).getMsgTitle());
                            view.findViewById(R.id.tvNew0).setVisibility(notificationListItemBeans.get(0).getIsNew() == 1 ? View.VISIBLE : View.GONE);
                            view.findViewById(R.id.tvNew1).setVisibility(notificationListItemBeans.get(1).getIsNew() == 1 ? View.VISIBLE : View.GONE);
                            view.findViewById(R.id.tvNew2).setVisibility(notificationListItemBeans.get(2).getIsNew() == 1 ? View.VISIBLE : View.GONE);
//                            view.findViewById(R.id.tvNew0).setVisibility(1 == 1 ? View.VISIBLE : View.GONE);
//                            view.findViewById(R.id.tvNew1).setVisibility(1 == 1 ? View.VISIBLE : View.GONE);
//                            view.findViewById(R.id.tvNew2).setVisibility(1 == 1 ? View.VISIBLE : View.GONE);
                            return view;
                        }
                    })
                    .toList()
                    .subscribe(new SingleObserver<List<View>>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onSuccess(List<View> views) {
                            Logger.d("initNotificationView onSuccess : " + views.size());
                            getView().initNoticeMarquee(views);
                        }

                        @Override
                        public void onError(Throwable e) {
                            Logger.d("initNotificationView onError : " + e.getMessage());
                        }
                    });
        }

        public Observable<User> getUserObservable() {
            return userObservable;
        }

        public ArrayList<AdvertisementBean> getAdvertisementBeans() {
            return advertisementBeans;
        }

        /**
         * 检测是否有权限进入总裁热线
         */
        public void checkPermissionForPresidentOnline(final boolean startPresidentOnlinePage) {
            String phone = "";
            User user = UserSession.getInstance().getUser();
            if (user != null) {
                phone = user.getPhone();
            }

            RetrofitManager.getInstance().createOpenApiService(PresidentOnlineService.class)
                    .judgeJurisdiction(new RequestPermissionForPresidentOnlineBean(phone))
                    .compose(getView().<OpenApiResult<PermissionForPresidentOnlineBean>>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<PermissionForPresidentOnlineBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                            //getView().onLoading();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                        }

                        @Override
                        public void onLoaded() {
                        }

                        @Override
                        public void onSuccess(OpenApiResult<PermissionForPresidentOnlineBean> result, PermissionForPresidentOnlineBean datas) {
                            if (datas != null) {
                                getView().onPresidentOnlinePermission(datas, startPresidentOnlinePage);
                            }
                        }

                        @Override
                        public void onApiError(OpenApiResult<PermissionForPresidentOnlineBean> result, int code, String msg) {

                        }
                    });
        }

        /**
         * 检测是否有权限进入月结运费查询
         */
        public void checkPermissionForQueryFreightRates(boolean startFreightRatesPage) {
            String phone = "";
            String customerCode = "";
            User user = UserSession.getInstance().getUser();
            if (user != null) {
                phone = user.getPhone();
                customerCode = user.getCustomCode();
            }

            RetrofitManager.getInstance().createOpenApiService(FreightRatesQueryService.class)
                    .permissionQueryCost(new RequestPermissionQueryCostBean(phone, customerCode))
                    .compose(getView().<OpenApiResult<PermissionQueryCostResultBean>>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<PermissionQueryCostResultBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                            //getView().onLoading();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                        }

                        @Override
                        public void onLoaded() {
                        }

                        @Override
                        public void onSuccess(OpenApiResult<PermissionQueryCostResultBean> result, PermissionQueryCostResultBean datas) {
                            if (datas != null) {
                                getView().onPermissionForQueryFreightRates(result, startFreightRatesPage);
                            }
                        }

                        @Override
                        public void onApiError(OpenApiResult<PermissionQueryCostResultBean> result, int code, String msg) {

                        }
                    });
        }

        /**
         * 月结运费查询---自动带出客户编码及密码
         */
        public void getCustomerInfo() {
            String phone = "";
            User user = UserSession.getInstance().getUser();
            if (user != null) {
                phone = user.getPhone();
            }

            RetrofitManager.getInstance().createOpenApiService(FreightRatesQueryService.class)
                    .getCustomerInfo(new RequestGetCustomerInfoBean(phone))
                    .compose(getView().<OpenApiResult<GetCustomerInfoResultBean>>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<GetCustomerInfoResultBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                            getView().onGetCustomerInfoLoading();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onGetCustomerInfoError(getView().getContext().getString(R.string.common_net_error));
                        }

                        @Override
                        public void onLoaded() {
                            if (getView() != null) {
                                getView().onGetCustomerInfoComplete();
                            }
                        }

                        @Override
                        public void onSuccess(OpenApiResult<GetCustomerInfoResultBean> result, GetCustomerInfoResultBean datas) {
                            if (datas != null) {
                                getView().onGetCustomerInfoLoaded(datas);
                            }
                        }

                        @Override
                        public void onApiError(OpenApiResult<GetCustomerInfoResultBean> result, int code, String msg) {
                            if (!TextUtils.isEmpty(msg)) {
                                getView().onGetCustomerInfoError(msg);
                            } else {
                                getView().onGetCustomerInfoError(getView().getContext().getString(R.string.common_net_error));
                            }
                        }
                    });
        }

        /**
         * 检测是否有权限进入[预存运费]模块
         */
        void checkPermissionForDeposit() {
            User user = UserSession.getInstance().getUser();

            if (user == null || !user.isLogin()) {
                ToastManager.showCenterForShort("请先登录");
                LoginActivity.startActivity(mContext);
                return;
            }

            if ((user.getMarketer() == null || user.getMarketer().equals("")) && (user.getAssistant() == null || user.getAssistant().equals(""))) {
                ToastManager.showCenterForShort("目前暂无法使用预存功能，请联系您的跨越专员");
                return;
            }

            if (null == user.getCustomCode() || 0 >= user.getCustomCode().length()) {
                ToastManager.showCenterForShort("您还未绑定客户编码");
                BindCustomerCodeActivity.startActivity(getView().getContext());
                return;
            }

            String phone = user.getPhone();
            String companyCode = user.getCustomCode();
            RetrofitManager.getInstance().createOpenApiService(DepositService.class)
                    .judgeStoredQuery(new RequestJudgeStoredQuery(companyCode, phone))
                    .compose(getView().bindToLifecycleDestroy())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<ResultJudgeStoredQueryBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                            getView().onDepositLoading();
                        }

                        @Override
                        public void onLoaded() {
                            getView().onDepositComplete();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<ResultJudgeStoredQueryBean> result, ResultJudgeStoredQueryBean data) {
                            getView().onDepositSuccess(result);
                        }

                        @Override
                        public void onApiError(OpenApiResult<ResultJudgeStoredQueryBean> result, int code, String msg) {
                            getView().onDepositError(result,code,msg);
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onDepositOtherError(e);
                        }
                    });
        }

        /**
         * 获取并绑定用户信息
         */
        public void getUserInfo() {
            userObservable
                    .subscribe(new Consumer<User>() {
                        @Override
                        public void accept(User user) throws Exception {
                            userInfo = user;
                            getView().onUser(userInfo);
                        }
                    });
        }

        public void getLogisticsSendAndReceiveRecords(User user) {
            RequestLogisticsSendAndReceiveRecords requestLogisticsSendAndReceiveRecords = new RequestLogisticsSendAndReceiveRecords(user.getPhone());
            logisticsDataSource
                    .getLogisticsSendAndReceiveRecords(requestLogisticsSendAndReceiveRecords)
                    .compose(getView().<OpenApiResult<LogisticsSendAndReceiveRecordBean>>bindToLifecycleDestroy())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<LogisticsSendAndReceiveRecordBean>() {
                        @Override
                        public void onLoading(Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onSuccess(OpenApiResult<LogisticsSendAndReceiveRecordBean> result, LogisticsSendAndReceiveRecordBean logisticsSendAndReceiveRecordBeans) {
                            getView().updateLogisticsSendAndReceiveRecords(logisticsSendAndReceiveRecordBeans);
                        }

                        @Override
                        public void onApiError(OpenApiResult<LogisticsSendAndReceiveRecordBean> result, int code, String msg) {
                            /**
                             * 失败不现实
                             */
                            getView().getLogisticsSendAndReceiveRecordsFailed(result);
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            /**
                             * 失败不现实
                             */
                            getView().getLogisticsSendAndReceiveRecordsFailed(e);
                        }

                        @Override
                        public void onLoaded() {

                        }
                    });
        }

//        private void updateLogisticsSendAndReceiveRecords(List<LogisticsSendAndReceiveRecordBean> logisticsSendAndReceiveRecordBeans) {
//            /**
//             * 待取货数量
//             */
//            Single<Integer> toTake = Observable.fromIterable(logisticsSendAndReceiveRecordBeans)
//                    .filter(new Predicate<LogisticsSendAndReceiveRecordBean>() {
//                        @Override
//                        public boolean test(LogisticsSendAndReceiveRecordBean logisticsSendAndReceiveRecordBean) throws Exception {
//                            return logisticsSendAndReceiveRecordBean.getStatus() == LogisticsRecordStatusType.Status.TO_TAKE;
//                        }
//                    })
//                    .reduce(0, new BiFunction<Integer, LogisticsSendAndReceiveRecordBean, Integer>() {
//                        @Override
//                        public Integer apply(Integer integer, LogisticsSendAndReceiveRecordBean logisticsSendAndReceiveRecordBean) throws Exception {
//                            return integer + logisticsSendAndReceiveRecordBean.getCount();
//                        }
//                    });
//            /**
//             * 待签收数量
//             */
//            Single<Integer> toSign = Observable.fromIterable(logisticsSendAndReceiveRecordBeans)
//                    .filter(new Predicate<LogisticsSendAndReceiveRecordBean>() {
//                        @Override
//                        public boolean test(LogisticsSendAndReceiveRecordBean logisticsSendAndReceiveRecordBean) throws Exception {
//                            return logisticsSendAndReceiveRecordBean.getStatus() == LogisticsRecordStatusType.Status.TO_SIGN;
//                        }
//                    })
//                    .reduce(0, new BiFunction<Integer, LogisticsSendAndReceiveRecordBean, Integer>() {
//                        @Override
//                        public Integer apply(Integer integer, LogisticsSendAndReceiveRecordBean logisticsSendAndReceiveRecordBean) throws Exception {
//                            return integer + logisticsSendAndReceiveRecordBean.getCount();
//                        }
//                    });
//            /**
//             * 今日签收
//             */
//            Single<Integer> signToday = Observable.fromIterable(logisticsSendAndReceiveRecordBeans)
//                    .filter(new Predicate<LogisticsSendAndReceiveRecordBean>() {
//                        @Override
//                        public boolean test(LogisticsSendAndReceiveRecordBean logisticsSendAndReceiveRecordBean) throws Exception {
//                            return logisticsSendAndReceiveRecordBean.getStatus() == LogisticsRecordStatusType.Status.SIGN_TODAY;
//                        }
//                    })
//                    .reduce(0, new BiFunction<Integer, LogisticsSendAndReceiveRecordBean, Integer>() {
//                        @Override
//                        public Integer apply(Integer integer, LogisticsSendAndReceiveRecordBean logisticsSendAndReceiveRecordBean) throws Exception {
//                            return integer + logisticsSendAndReceiveRecordBean.getCount();
//                        }
//                    });
//            Single
//                    .zip(toTake, toSign, signToday, new Function3<Integer, Integer, Integer, RecordAmountModel>() {
//                        @Override
//                        public RecordAmountModel apply(Integer toTake, Integer toSign, Integer signToday) throws Exception {
//                            return new RecordAmountModel(toTake, toSign, signToday);
//                        }
//                    })
//                    .compose(getView().<RecordAmountModel>bindToLifecycleDestroy())
//                    .subscribeOn(Schedulers.io())
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe(new SingleObserver<RecordAmountModel>() {
//                        @Override
//                        public void onSubscribe(Disposable d) {
//
//                        }
//
//                        @Override
//                        public void onSuccess(RecordAmountModel recordAmountModel) {
//                            getView().updateLogisticsRecordSendAndReceive(recordAmountModel);
//                        }
//
//                        @Override
//                        public void onError(Throwable e) {
//
//                        }
//                    });
//        }

        public void refreshLogisticsRecordSendReceive() {
            if (userInfo != null && userInfo.isLogin()) {
                getLogisticsSendAndReceiveRecords(userInfo);
            }
        }

    }
}
